package cn.jbolt.codegen.util;

import cn.hutool.core.io.FileUtil;
import cn.jbolt.core.model.DictionaryType;
import cn.jbolt.core.util.JBoltStringUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import com.jfinal.template.ext.directive.NowDirective;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 本系统中定义的字典类型typeKey生成
 * 快捷生成枚举到DictionaryTypeKey.java文件中，
 * 方便其他地方统一调用
 */
public class JBoltDictionaryTypeKeyGen {
	public static final JBoltDictionaryTypeKeyGen me= new JBoltDictionaryTypeKeyGen();
	public final String SEPARATOR=File.separator;
	/**
	 * JBolt项目绝对路径 修改这个就行
	 */
	private final String PROJECT_PATH=System.getProperty("user.dir");
	/**
	 * DictionaryTypeKey.java的绝对路径
	 */
	private final String TARGET=PROJECT_PATH+SEPARATOR+"jbolt_extend"+SEPARATOR+"src"+SEPARATOR+"main"+SEPARATOR+"java"+SEPARATOR+"cn"+SEPARATOR+"jbolt"+SEPARATOR+"extend"+SEPARATOR+"dictionary"+SEPARATOR+"DictionaryTypeKey.java";
	/**
	 * 模板绝对路径
	 */
	private final String TPL=PROJECT_PATH+SEPARATOR+"jbolt_code_generator"+SEPARATOR+"src"+SEPARATOR+"main"+SEPARATOR+"resources"+SEPARATOR+"gentpl"+SEPARATOR+"dictionary_type_key_template.jf";

	public Ret gen() {
		List<DictionaryType> types = new DictionaryType().dao().findAll();
		Engine engine = new Engine();
		engine.addSharedObject("JBoltStringUtil", new JBoltStringUtil());
		engine.addDirective("now", NowDirective.class,true);
		Template template=engine.getTemplate(TPL);
		BufferedWriter writer=FileUtil.getWriter(TARGET, "utf-8", false);
		try {
			writer.write(template.renderToString(Kv.by("types", types)));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			return Ret.fail("生成失败");
		}finally {
			if(writer!=null){
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
					return Ret.fail("生成失败");
				}
				}


		}
	return Ret.ok("操作成功");

	}
}
